package com.xz;

import org.junit.Test;

/**
 * @author XZ
 * @create 2021-04-19 11:09
 * https://leetcode-cn.com/problems/reverse-linked-list/
 */
public class _206_反转链表 {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode newHead = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }

    @Test
    public void test() {
        ListNode l5 = new ListNode(5);
        ListNode l4 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        ListNode l2 = new ListNode(2);
        ListNode l1 = new ListNode(1);
        l5.next = l4;
        l4.next = l3;
        l3.next = l2;
        l2.next = l1;

        _206_反转链表 v = new _206_反转链表();
        ListNode listNode = v.reverseList2(l5);
        System.out.println(listNode.toString());
    }
}
